/*
 *
   gcc 2.c -L. -lGLESv2 -lmingw32 -lSDL2_test -lSDL2main -lSDL2 -lSDL2_ttf && a 
   gcc 2.c SDL_test_common.c -lm -lSDL2 -lSDL2_ttf && ./a.out &&
   gcc 2.c -llibGLESv2 -lSDL2_test -lm -lmingw32 -lSDL2main -lSDL2   && a
   adb push 2.c /sdcard/ &&
   Copyright (r) 1997-2014 Sam Lantinga <slouken@libsdl.org>

   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
   arising from the use of this software.

   Permission is granted to anyone to use this software for any purpose,
   including commercial applications, and to alter it and redistribute it
   freely.
   */
#include "gles2base.h"
#include "SDL2/SDL.h"

void Draw(UserData*userData) 
{
	ctx.glViewport(0, 0, state->window_w, state->window_h);
	ctx.glClear(GL_COLOR_BUFFER_BIT); 
	ctx.glUseProgram(userData->programObject); 

	GLfloat vVertices[] = {
		0.0f, 0.5f, 0.0f, 
		-0.5f, -0.5f, 0.0f, 
		0.5f, -0.5f, 0.0f}; 

	ctx.glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vVertices); 
	ctx.glEnableVertexAttribArray(0); 
	ctx.glDrawArrays(GL_TRIANGLES, 0, 3); 
} 

int Init(UserData*userData)
{ 
	GLbyte vShaderStr[] =  
		"attribute vec4 vPosition;    \n"
		"void main()                  \n"
		"{                            \n"
		"   gl_Position = vPosition;  \n"
		"}                            \n";

	GLbyte fShaderStr[] =  
		"precision mediump float;\n"
		"void main()                                  \n"
		"{                                            \n"
		"  gl_FragColor = vec4 ( 1.0, 0.0, 0.0, 1.0 );\n"
		"}";
	GLint linked; 
	userData->shader_vert= LoadShader(GL_VERTEX_SHADER, vShaderStr); 
	userData->shader_frag= LoadShader(GL_FRAGMENT_SHADER,fShaderStr);
	userData->programObject= ctx.glCreateProgram(); 
	if(!userData->programObject) 
		return 0; 
	ctx.glAttachShader(userData->programObject, userData->shader_vert); 
	ctx.glAttachShader(userData->programObject, userData->shader_frag); 
	ctx.glBindAttribLocation(userData->programObject, 0, "vPosition"); 
	ctx.glLinkProgram(userData->programObject); 
	ctx.glGetProgramiv(userData->programObject, GL_LINK_STATUS, &linked); 
	if(!linked) 
	{ 
		GLint infoLen = 0; 
		ctx.glGetProgramiv(userData->programObject, GL_INFO_LOG_LENGTH, &infoLen); 
		if(infoLen > 1) 
		{ 
			char* infoLog = malloc(sizeof(char) * infoLen); 
			/*ctx.glGetProgramInfoLog(userData->programObject, infoLen, NULL, infoLog); */
			SDL_Log("Error linking program:\n%s\n", infoLog); 
			free(infoLog); 
		} 
		ctx.glDeleteProgram(userData->programObject);
		return 0; 
	} 
	ctx.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); 
	return 1; 
}
